#!/usr/local/bin/perl
package SND;
use strict; use warnings;

use Glib qw/TRUE FALSE/;
use Gtk2;
use GStreamer -init;

#-------------------------------------------------------------------

my $loop;
my @plays;
my $file;
my $tid;

sub init_snd
{
    my $k=-1;
    $loop = Glib::MainLoop -> new();
    foreach("page.mp3","slide.mp3","stop.mp3","start.mp3","end.mp3","pop.mp3"){
	$k++;
	$plays[$k] = GStreamer::ElementFactory -> make("playbin", "play$k");
	eval{
	    $plays[$k] -> set(uri => Glib::filename_to_uri "$_[0]/$_", "localhost");
	};
	if($@){
	    undef $plays[$k];
	    undef $loop;
	}else{
	    $plays[$k] -> get_bus() -> add_watch(\&my_bus_callback, $loop);
	}
    }
    return \$loop;
}

sub end_snd
{
    foreach(@plays){
	$_ -> set_state("null") if defined $_;
    }
    $loop->quit();
    foreach(@plays){
	undef $_ if defined $_;
    }
    undef $loop;
}

sub play_snd
{
    return FALSE unless defined $plays[$_[0]];
    return FALSE if defined $tid;
    $tid=Glib::Idle->add(sub
		    {
			return FALSE unless defined $plays[$_[0]];
			$plays[$_[0]] -> set_state("playing");
			return FALSE unless defined $loop;
			$loop -> run();
			return FALSE unless $plays[$_[0]];
			$plays[$_[0]] -> set_state("null");
			undef $tid;
			return FALSE;
		    }
	,$_[0]);
}

sub my_bus_callback
{
    my ($bus, $message, $loop) = @_;
    if ($message -> type & "error") {
	warn $message -> error;
	$loop -> quit();
    }
    elsif ($message -> type & "eos") {
	$loop -> quit();
    }
    return TRUE;
}

1;
